package org.midy.nio;

import org.midy.infrastructure.tools.Logger;

import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.CountDownLatch;

public class ServerSocketChannelTestMain {

    public static void main(String[] args) {
        try {
            ServerSocketChannel serverChannel = ServerSocketChannel.open();
            serverChannel.bind(new InetSocketAddress(8090));
            serverChannel.configureBlocking(false);
            Logger.info("1 serverChannel.isOpen() = %b", serverChannel.isOpen());

            Selector open = Selector.open();
            serverChannel.register(open, SelectionKey.OP_ACCEPT);
            open.select();
            SocketChannel accept = serverChannel.accept();

            Logger.info("client.isOpen() = %b", accept.isOpen());
            accept.shutdownInput();
            Logger.info("shutdownInput client.isOpen() = %b", accept.isOpen());
            accept.shutdownOutput();
            Logger.info("shutdownOutput client.isOpen() = %b", accept.isOpen());
            accept.close();
            Logger.info("close client.isOpen() = %b", accept.isOpen());
            Logger.info("client.isConnected() = %b", accept.isConnected());

            CountDownLatch countDownLatch = new CountDownLatch(1);
            countDownLatch.await();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
